// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'yiibook-pro-yo19d'
})

// 云函数入口函数
exports.main = async (event, context) => {
  var result = await cloud.database().collection('exams').where({
    examDate: date()
  }).get()
  var exams = result.data
  var updateds = [];
  var subscribesArr = [];
  var sends = [];
  // 测试日志
  var log = {
    date: date(),
    exams: exams
  }
  for(var i = 0; i < exams.length; i++) {
    result = await cloud.database().collection('subscribes').where({
      examId: exams[i]._id,
      isSend: 0
    }).get()
    var subscribes = result.data
    subscribesArr.push(subscribes)
    for(var j = 0; j < subscribes.length; j++) {
      var sendRes = await send(exams[i], subscribes[j])
      sends.push(sendRes)
      const updated = await cloud.database().collection('subscribes').doc(subscribes[j]._id)
      .update({
        data: {
          isSend: 1
        }
      })
      updateds.push(updated)
    }
  }
  log.subscribesArr = subscribesArr,
  log.updateds = updateds
  log.sends = sends
  // 存储测试日志
  const logs = await cloud.database().collection('logs').add({
    data: log
  })
  // return log
}

const send = async (exam, subscribe) => {
  return await cloud.openapi.subscribeMessage.send({
    touser: subscribe.openid,
    page: 'pages/index/index',
    lang: 'zh_CN',
    data: {
      thing3: {
        value: exam.courseName
      },
      date1: {
        value: exam.startTime
      },
      thing2: {
        value: exam.examAddress
      },
      thing5: {
        value: '按时参考，诚信应考，严肃考风考纪'
      }
    },
    templateId: 'Ss6dzyGWZYkFf5lwJofeeht0l1dt8nQJmBdwD9zS8Z4',
  })
}

const date = () => {
  var date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}